import router from './index';
import {getToken} from '../utils/auth';
import {useUserStore, useMainStore} from '@/store/index.js'
import {DynamicRoutes, constantRoutes} from './index.js'
import Layout from "@/layout/index.vue";

const whiteList = ['/login', '/register']
/**
 * 前置路由守卫
 */
/*https://juejin.cn/post/6844903478880370701*/
router.beforeEach((to, from, next) => {
    // console.log('全部路由 :>> ', router.getRoutes());
    const mainStore = useMainStore()
    const userStore = useUserStore()
    if(to.meta.title){
        mainStore.pageName = to.meta.title
    }
    if (userStore.token) { // 判断是否有token
        if (to.path === '/login') {
            next({path: '/home'});
        } else {
            if (mainStore.routes.length === 0) {
                userStore.getMeInfo().then(res => { // 拉取info
                    // console.log('用户信息 :>> ', res);
                    const roles = res.roles;
                    // console.log('roles :>> ', roles);
                    // 添加路由
                    GenerateRoutes(roles).then(r => {
                        for (let i = 0; i < r.length; i++) {
                            router.addRoute(r[i])
                        }
                    })
                    next({...to, replace: true})
                }).catch(err => {
                    console.log(err);
                });
            } else {
                next() //当有用户权限的时候，说明所有可访问路由已生成 如访问没权限的全面会自动进入404页面
            }
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
            next();
        } else {
            next('/login'); // 否则全部重定向到登录页
        }
    }
});


function GenerateRoutes(roles) {
    return new Promise(resolve => {
        const accessedRouters = DynamicRoutes.filter(v => {
            if (roles.indexOf('admin') >= 0) return true;
            if (hasPermission(roles, v)) {
                if (v.children && v.children.length > 0) {
                    v.children = v.children.filter(child => {
                        if (hasPermission(roles, child)) {
                            return child
                        }
                        return false;
                    });
                    return v
                } else {
                    return v
                }
            }
            return false;
        });
        // console.log('accessedRouters :>> ', accessedRouters);
        const mainStore = useMainStore()
        mainStore.routes = accessedRouters;
        resolve(accessedRouters);
    })
}


function hasPermission(roles, route) {
    if (route.meta && route.meta.role) {
        return roles.some(role => route.meta.role.indexOf(role) >= 0)
    } else {
        return true
    }
}
